import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Card, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { authApi } from '../../api';

const AdminLogin = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    // 如果已经登录且是管理员，直接跳转到管理后台
    if (authApi.isAuthenticated() && authApi.isAdmin()) {
      navigate('/admin/dashboard');
    }
  }, [navigate]);

  const onFinish = async (values) => {
    setLoading(true);
    try {
      const response = await authApi.login(values.username, values.password);
      if (response.success) {
        const currentUser = authApi.getCurrentUser();
        if (currentUser && currentUser.role === 'ADMIN') {
          message.success('登录成功');
          navigate('/admin/dashboard');
        } else {
          message.error('您不是管理员，无法访问后台管理系统');
          authApi.logout(); // 清除非管理员的登录信息
        }
      } else {
        message.error(response.message || '登录失败，请检查用户名和密码');
      }
    } catch (error) {
      message.error('登录失败，请稍后再试');
      console.error('登录错误:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      height: '100vh',
      background: '#f0f2f5'
    }}>
      <Card 
        title="图书商城管理系统" 
        style={{ width: 400 }}
        headStyle={{ 
          textAlign: 'center', 
          fontSize: '24px', 
          fontWeight: 'bold' 
        }}
      >
        <Form
          name="admin_login"
          initialValues={{ 
            username: 'admin',
            password: 'admin123'
          }}
          onFinish={onFinish}
          size="large"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input 
              prefix={<UserOutlined />} 
              placeholder="用户名" 
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
            />
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              style={{ width: '100%' }}
              loading={loading}
            >
              登录
            </Button>
          </Form.Item>
          
          <div style={{ textAlign: 'center' }}>
            <p>默认管理员账号：admin / admin</p>
          </div>
        </Form>
      </Card>
    </div>
  );
};

export default AdminLogin; 